import { darkCssIsReady, loadDarkThemeCss } from 'vite-plugin-theme/es/client'
import { addClass, hasClass, removeClass } from './util'
import { DarkModeEnum } from '@/types/settings'

export async function updateDarkTheme(
  mode: string | DarkModeEnum = DarkModeEnum.LIGHT
) {
  const htmlRoot = document.getElementById('htmlRoot')
  if (!htmlRoot) {
    return
  }
  const hasDarkClass = hasClass(htmlRoot, DarkModeEnum.DARK)
  if (mode === DarkModeEnum.DARK) {
    if (import.meta.env.PROD && !darkCssIsReady) {
      await loadDarkThemeCss()
    }
    htmlRoot.setAttribute('data-theme', DarkModeEnum.DARK)
    if (!hasDarkClass) {
      addClass(htmlRoot, DarkModeEnum.DARK)
    }
  } else {
    htmlRoot.setAttribute('data-theme', DarkModeEnum.LIGHT)
    if (hasDarkClass) {
      removeClass(htmlRoot, DarkModeEnum.DARK)
    }
  }
}
